import { Pagination, Space, Spin } from 'antd';
import { useEffect } from "react";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
import { useHistory, useRouteMatch } from 'react-router';
import FeedItem from '../../componets/FeedItem';
import { useQuery } from '../../utils/hooks';
import { feedsPageSelector, feedsSelector, fetchFeedsPageAction } from "./feedsSlice";

export default function FeedsList() {
  const {url} = useRouteMatch()
  const history = useHistory()
  let {page: currentPage = 1} = useQuery()
  currentPage = +currentPage
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(fetchFeedsPageAction(currentPage))
  }, [dispatch, currentPage])
  const feedsState = useSelector(feedsSelector)
  const feeds = feedsPageSelector(feedsState, currentPage)
  const {count, loading} = feedsState

  return (
    <div>
      {
        loading && feeds.length === 0? (
          <Space size="middle">
            < Spin size="large" />
          </Space>) :
          feeds.map(feed => (
                <FeedItem key={feed.id} feed={feed}/>
              ))
      }
      {
        count > 0 && (<Pagination
          style={{paddingTop: 10}}
          total={count} limit={10}
          current={currentPage}
          showSizeChanger={false}
          onChange={(page) => {
            history.push(url + '?page=' + page)
          }} />
        )
      }

    </div>
  )
}